package com.suez.nullpointerexception.blizzard.cserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Date;

import com.suez.nullpointerexception.blizzard.global.Global;

public class ClientRunnable implements Runnable{
	
	private InputStream is;	
	private Socket socket;
	public ClientRunnable (Socket socket){
		this.socket = socket;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		Date date = new Date();
		Global.socketPool.add(socket);
		Global.userMsg.put(socket.getRemoteSocketAddress().toString().replaceAll("/", ""),date);						
		System.out.println(socket.getRemoteSocketAddress().toString()+"    "+date.toString());			
		while("on".equals(Global.logMsg) && !socket.isClosed()){
			try {			
			is= socket.getInputStream();			
			BufferedReader reader;		
			reader = new BufferedReader(new InputStreamReader(is,"utf-8"));			
			String protocol = reader.readLine();
			System.out.println(protocol);
			//System.out.println(tep);
			//System.out.println(action);
			if(protocol==null){socket.close();System.exit(0);}
			try{
				Global.controllers.get(protocol.split("-")[0]).execute(socket,protocol);
			}catch(NullPointerException e){
				System.err.println("Error!");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//System.err.println("Server is off!");System.exit(0);
				try {
					socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
			}
	}
	
}
